<template>
  <div class="maintenanceregist pd30 propertyMaintenance">
    <div class="panelWrap">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>维保公司备案</div>
      </div>
      <div class="con flex">
        <div class="conLeft">
          <div class="inputLable inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>单位名称：</span>
            <el-input v-model="maintenance.name" class="input" placeholder="请输入单位名称" />
          </div>
          <div class="inputLable inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>统一社会信用代码：</span>
            <el-input v-model="maintenance.socialCreditCode" class="input" placeholder="请输入统一社会信用代码" />
          </div>
          <div class="inputLable inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>应急救援电话：</span>
            <el-input v-model="maintenance.rescuePhone" class="input" placeholder="请输入应急救援电话" />
          </div>
          <div class="inputLable inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>主要负责人：</span>
            <el-input v-model="maintenance.chargePerson" class="input" placeholder="请输入主要负责人" />
          </div>
          <div class="inputLable inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>坐标：</span>
            <el-input class="input coordinateRead" :value="getcoordinate" readonly placeholder="请选择坐标" />
            <el-button class="locationBtn locaBtn el-icon-location-information" @click="choiceCoordinate=true">定位</el-button>
          </div>
          <div class="inputLable inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>注册地址：</span>
            <el-input v-model="maintenance.address" class="input" placeholder="请输入注册地址" />
          </div>
          <div class="inputLable inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>办公地址：</span>
            <el-input v-model="maintenance.officeAddress" class="input" placeholder="请输入办公地址" />
          </div>
          <div class="inputLable wd100 inputLable1 flex ">
            <span class="name texttr"><span class="mustval">*</span>请输入公司介绍：</span>
            <textarea v-model="maintenance.introduce" class="markinfo" />
          </div>
        </div>
        <div class="conRight">
          <div class="uploadwrap">
            <div class="titleTip">
              请上传相关证书及申请表
            </div>
            <div class="row flex sanzhengImg">
              <div class="uploadDetails">
                <div class="">
                  <div class="uploadDetails-title">请上传营业执照扫描件</div>
                  <uploadImg imgtype="businessLicensePicFile" :pic-url="businessLicensePicIdBase64" @sendImginfo="handleImginfo" />
                </div>
              </div>
              <div class="uploadDetails">
                <div class="">
                  <div class="uploadDetails-title pre">请上传备案申请表扫描件<div class="downTem m-l-10"><span class="iconfont icon-xiazai" />申请表模板下载</div>
                  </div>
                  <uploadImg imgtype="applyTemplateFile" :pic-url="applyTemplateFileIdBase64" @sendImginfo="handleImginfo" />
                </div>
              </div>
            </div>
            <div class="titleTip m-t-35">
              请上传特种设备生产许可证或安装改造维修许可证扫描件
            </div>
            <div class="row flex">
              <div class="uploadDetails">
                <div class="">
                  <span class="uploadDetails-title">许可证</span>
                  <uploadImg imgtype="produceLicensePicFile" :pic-url="produceLicensePicIdBase64" @sendImginfo="handleImginfo" />
                </div>
              </div>
              <div class="uploadDetails">
                <div class="">
                  <span class="uploadDetails-title">扫描件</span>
                  <uploadImg imgtype="maintainLicensePicFile" :pic-url="maintainLicensePicIdBase64" @sendImginfo="handleImginfo" />
                </div>
              </div>
            </div>
          </div>
          <div class="inputLable wd100 inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>许可证编号：</span>
            <el-input v-model="maintenance.licenseCode" class="input" placeholder="请输入许可证编号" />
          </div>
          <div class="inputLable wd100 inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>许可项目：</span>
            <div class="flex ">
              <div v-for="(item,index) in licenseProjectArr" :key="index" class="m-r-25">
                <el-checkbox v-model="item.check" :checked="item.check" @change="handleObjtype(item,index)">{{ item.name }}</el-checkbox>
              </div>
            </div>
          </div>
          <div class="inputLable wd100 inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>许可证发证机关：</span>
            <el-input v-model="maintenance.licenseIssuingAuthority" class="input" placeholder="请输入许可证编号" />
          </div>

          <div class="inputLable wd100 inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>许可证发证日期：</span>
            <el-date-picker v-model="maintenance.licenseIssuingDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="请输入许可证编号" />
          </div>

          <div class="inputLable wd100 inputLable1 flex flexac">
            <span class="name texttr"><span class="mustval">*</span>许可证有效期至：</span>
            <el-date-picker v-model="maintenance.licenseExpiryDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="请输入许可证编号" />
          </div>
        </div>
      </div>
      <div class="flex  footerBtn m-t-35">
        <el-button v-if="!mainrenanceType" class="btn saveBtn el-icon-circle-check m-r-20" @click="handleSave(0)">保 存</el-button>
        <el-button v-else type="success" class="btn el-icon-circle-check m-r-20" @click="handleSave(1)">更 新</el-button>
        <!-- <el-button class="clsoeBtn btn el-icon-circle-close" @click="handleCloseDialogUpdate">关 闭</el-button> -->
      </div>
    </div>

    <el-dialog v-if="choiceCoordinate" custom-class="coordinateWrap" :close-on-click-modal="false" :visible.sync="choiceCoordinate">
      <coordinate />
    </el-dialog>

  </div>
</template>

<script>

import { unitfilingAdd, unitfilingUpload, unitfilingUpdate } from '@/api/maintenance/unitfiling'

import { showNotice, checkMobile, convertImgToBase64, dataURLtoFile } from '@/utils/toolclass'
import uploadImg from '@/components/uploadImg'
import coordinate from '@/components/coordinate'
import bus from '@/utils/bus'
import storage from '@/utils/storage'

export default {
  components: { uploadImg, coordinate },
  props: {
    addFactory: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean
    }
  },
  data() {
    return {
      choiceCoordinate: false,
      maintenance: {},
      mainrenanceType: false,
      licenseProjectArr: [
        {
          id: 1,
          check: true,
          name: '生产'
        },
        {
          id: 1,
          check: false,
          name: '安装'
        },
        {
          id: 1,
          check: false,
          name: '改造'
        },
        {
          id: 1,
          check: false,
          name: '修理'
        }
      ],

      businessLicensePicIdBase64: '',
      applyTemplateFileIdBase64: '',
      produceLicensePicIdBase64: '',
      maintainLicensePicIdBase64: ''

    }
  },
  computed: {
    getcoordinate() {
      if (this.maintenance.longitude === '' || this.maintenance.latitude === '') {
        return ''
      } else {
        return ('' + this.maintenance.longitude) + ' , ' + (this.maintenance.latitude + '')
      }
    }
  },
  created() {
    this.onCloseCoordinate()
    this.onSendCoordinate()
    // console.log('获取路由参数')
    this.maintenance.businessLicensePicId = ''
    this.maintenance.applyTemplateFileId = ''
    this.maintenance.produceLicensePicId = ''
    this.maintenance.maintainLicensePicId = ''
    // console.log(this.$route.query.obj)
    if (this.$route.query.obj.id !== '') {
      this.maintenance = this.$route.query.obj
      this.mainrenanceType = true
      this.convertImgToBase('http://39.107.41.165:8003/masterdata/file/picturePreview?id=' + this.maintenance.businessLicensePicId + '&rate=10', 'businessLicensePicId')
      this.convertImgToBase('http://39.107.41.165:8003/masterdata/file/picturePreview?id=' + this.maintenance.applyTemplateFileId + '&rate=10', 'applyTemplateFileId')
      this.convertImgToBase('http://39.107.41.165:8003/masterdata/file/picturePreview?id=' + this.maintenance.produceLicensePicId + '&rate=10', 'produceLicensePicId')
      this.convertImgToBase('http://39.107.41.165:8003/masterdata/file/picturePreview?id=' + this.maintenance.maintainLicensePicId + '&rate=10', 'maintainLicensePicId')
    } else {
      this.maintenance = this.$route.query.obj
      this.mainrenanceType = false
    }
  },
  mounted() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/record' }))
    this.recordData = JSON.parse(storage.get('userInfo'))
  },
  methods: {
    convertImgToBase(url, type) {
      // console.log(url)
      const that = this
      convertImgToBase64(url, function(base64Img) {
        if (type === 'businessLicensePicId') {
          that.businessLicensePicIdBase64 = base64Img
          that.maintenance.applyTemplateFile = dataURLtoFile(base64Img)
        } else if (type === 'applyTemplateFileId') {
          that.applyTemplateFileIdBase64 = base64Img
          that.maintenance.businessLicensePicFile = dataURLtoFile(base64Img)
        } else if (type === 'produceLicensePicId') {
          that.produceLicensePicIdBase64 = base64Img
          that.maintenance.maintainLicensePicFile = dataURLtoFile(base64Img)
        } else if (type === 'maintainLicensePicId') {
          that.maintainLicensePicIdBase64 = base64Img
          that.maintenance.produceLicensePicFile = dataURLtoFile(base64Img)
        }
      })
    },
    handleObjtype(res, index) {
      this.licenseProjectArr.forEach((element, eindex) => {
        if (eindex !== index) {
          element.check = false
        }
      })
    },
    onSendCoordinate() {
      bus.$on('sendCoordinate', (data) => {
        this.maintenance.longitude = data.lng
        this.maintenance.latitude = data.lat
        this.handleCloseCoordinate()
      })
      bus.$on('sendCoordinateAddress', (data) => {
        // console.log('sendCoordinateAddress')
        // console.log(data)
        this.maintenance.address = (data.province === undefined ? '' : data.province) + '' + (data.city === undefined ? '' : data.city) + '' + (data.title === undefined ? '' : data.title)
        this.maintenance.officeAddress = (data.province === undefined ? '' : data.province) + '' + (data.city === undefined ? '' : data.city) + '' + (data.title === undefined ? '' : data.title)
      })
    },
    onCloseCoordinate() {
      bus.$on('closeCoordinate', (data) => {
        this.handleCloseCoordinate()
      })
    },
    handleCloseCoordinate() {
      this.choiceCoordinate = false
    },

    handleDelerow() {
      this.maintenanceList.pop()
    },
    handleImginfo(res) {
      // console.log('监听到图片组件返回信息')
      // console.log(res)
      if (res.imgType === 'applyTemplateFile') {
        // this.maintenance.applyTemplateFile=dataURItoBlob(res.base64Val);
        this.maintenance.applyTemplateFile = res.imgfile
      } else if (res.imgType === 'businessLicensePicFile') {
        // this.maintenance.businessLicensePicFile=dataURItoBlob(res.base64Val);
        this.maintenance.businessLicensePicFile = res.imgfile
      } else if (res.imgType === 'maintainLicensePicFile') {
        // this.maintenance.maintainLicensePicFile=dataURItoBlob(res.base64Val);
        this.maintenance.maintainLicensePicFile = res.imgfile
      } else if (res.imgType === 'produceLicensePicFile') {
        // this.maintenance.produceLicensePicFile=dataURItoBlob(rs.base64Val);
        this.maintenance.produceLicensePicFile = res.imgfile
      }
    },
    // handleUpdate() {
    //   simpleViewUpdate(this.addFactory).then((res) => {
    //     if (res.code == '000000') {
    //       showNotice('success', '提示', '保存成功')
    //       this.$emit('handleRefresh')
    //       this.$emit('handleCloseDialog')
    //     }
    //   })
    // },
    handleSave(type) {
      const licenseProject = this.licenseProjectArr.forEach((item) => {
        if (item.check) {
          this.maintenance.licenseProject = item.name
        }
      })
      if (this.maintenance.name === '') {
        showNotice('error', '提示', '单位名称不能为空')
        return
      }
      if (this.maintenance.socialCreditCode === '') {
        showNotice('error', '提示', '统一社会信用代码不能为空')
        return
      }

      if (this.maintenance.socialCreditCode.length !== 18) {
        showNotice('error', '提示', '统一社会信用代码长度为18位')
        return
      }

      if (this.maintenance.rescuePhone === '') {
        showNotice('error', '提示', '应急救援电话不能为空')
        return
      }
      if (!checkMobile(this.maintenance.rescuePhone)) {
        showNotice('error', '提示', '应急救援电话手机格式不对')
        return
      }

      if (this.maintenance.chargePerson === '') {
        showNotice('error', '提示', '主要负责人不能为空')
        return
      }
      if (this.maintenance.address === '') {
        showNotice('error', '提示', '注册地址不能为空')
        return
      }
      if (this.maintenance.officeAddress === '') {
        showNotice('error', '提示', '办公地址不能为空')
        return
      }

      if (this.maintenance.introduce === '') {
        showNotice('error', '提示', '公司介绍不能为空')
        return
      }

      if (this.maintenance.licenseCode === '') {
        showNotice('error', '提示', '许可证编号不能为空')
        return
      }

      if (this.maintenance.licenseProject === '') {
        showNotice('error', '提示', '许可项目不能为空')
        return
      }
      if (this.maintenance.licenseIssuingAuthority === '') {
        showNotice('error', '提示', '发证机关不能为空')
        return
      }
      if (this.maintenance.licenseIssuingDate === '') {
        showNotice('error', '提示', '许可证发证日期不能为空')
        return
      }
      if (this.maintenance.licenseExpiryDate === '') {
        showNotice('error', '提示', '许可证发证有效期不能为空')
        return
      }

      if (this.maintenance.applyTemplateFile === '') {
        showNotice('error', '提示', '备案申请表模板文件不能为空')
        return
      }
      if (this.maintenance.businessLicensePicFile === '') {
        showNotice('error', '提示', '营业执照扫描件图片不能为空')
        return
      }
      if (this.maintenance.maintainLicensePicFile === '') {
        showNotice('error', '提示', '安装改造维修许可证图片不能为空')
        return
      }

      if (this.maintenance.produceLicensePicFile === '') {
        showNotice('error', '提示', '特种设备生产许可证图片不能为空')
        return
      }
      console.log(this.maintenance)

      const params = {
        name: this.maintenance.name,
        socialCreditCode: this.maintenance.socialCreditCode,
        rescuePhone: this.maintenance.rescuePhone,
        chargePerson: this.maintenance.chargePerson,
        longitude: this.maintenance.longitude,
        latitude: this.maintenance.latitude,
        address: this.maintenance.address,
        officeAddress: this.maintenance.officeAddress,
        introduce: this.maintenance.introduce,
        licenseCode: this.maintenance.licenseCode,
        licenseProject: this.maintenance.licenseProject,
        licenseIssuingAuthority: this.maintenance.licenseIssuingAuthority,
        licenseIssuingDate: this.maintenance.licenseIssuingDate,
        licenseExpiryDate: this.maintenance.licenseExpiryDate,
        id: this.maintenance.id,
        version: this.maintenance.version,
        orgId: this.recordData.currentOrgId
        // auditState: '', // 复核状态
        // auditTime: '', // 复核时间
        // crtDate: '', // 提交时间
        // businessLicensePicId: '', // 营业执照扫描件图片ID
        // applyTemplateFileId: '', // 备案申请表模板文件ID
        // maintainLicensePicId: '', // 安装改造维修许可证图片ID
        // produceLicensePicId: '', // 特种设备生产许可证图片ID
      }

      if (type === 0) {
        this.handleMaintenanceAdd(params)
      } else {
        this.handleUpdate(params)
      }
    },
    handleUpdate(data) {
      unitfilingUpdate(data).then((res) => {
        if (res.code === '000000') {
          showNotice('success', '提示', '更新成功!')
          this.$emit('handleRefresh')
          this.$emit('handleCloseDialog')
          this.handleMaintenanceUpload(data.id, this.maintenance.applyTemplateFile,
            this.maintenance.businessLicensePicFile, this.maintenance.maintainLicensePicFile,
            this.maintenance.produceLicensePicFile
          )
        } else {
          if (res.msg === '失败') {
            showNotice('error', '提示', `更新${res.msg}`)
          } else {
            showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    handleCloseDialog() {
      // console.log('子组件关闭')
      this.$emit('handleCloseDialog')
    },
    handleCloseDialogUpdate() {
      this.$emit('handleRefresh')
      this.$emit('handleCloseDialog')
    },
    handleMaintenanceAdd(data) {
      unitfilingAdd(data).then((res) => {
        if (res.code === '000000') {
          showNotice('success', '提示', '保存成功!')
          this.$emit('handleRefresh')
          this.$emit('handleCloseDialog')
          this.handleMaintenanceUpload(res.data.id, this.maintenance.applyTemplateFile,
            this.maintenance.businessLicensePicFile, this.maintenance.maintainLicensePicFile,
            this.maintenance.produceLicensePicFile
          )
        } else {
          if (res.msg === '失败') {
            showNotice('error', '提示', `保存${res.msg}`)
          } else {
            showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    handleMaintenanceUpload(id, applyTemplateFile, businessLicensePicFile, maintainLicensePicFile, produceLicensePicFile) {
      // console.log(id, applyTemplateFile, businessLicensePicFile, maintainLicensePicFile, produceLicensePicFile)

      const formData = new FormData()
      formData.append('id', id)
      formData.append('applyTemplateFile', applyTemplateFile)
      formData.append('businessLicensePicFile', businessLicensePicFile)
      formData.append('maintainLicensePicFile', maintainLicensePicFile)
      formData.append('produceLicensePicFile', produceLicensePicFile)
      unitfilingUpload(formData).then((res) => {
        if (res.code === '000000') {
          // showNotice('success', '提示', '保存成功!')
          // this.$router.push({path:'/record',query:{obj:res.data}});
        }
      })
    }
  }
}
</script>

<style rel='stylesheet/scss' lang='scss' scoped>
@import "@/styles/addtable.scss";
.el-icon-circle-check:before {
  margin-right: 4px;
}
.inputLable .name {
  width: 140px !important;
  letter-spacing: 0px;
}
.btn {
  width: 100px;
  height: 40px;
}
.el-icon-location-outline:before {
  margin-right: 4px;
}
.locaBtn {
  height: 34px;
}
.panelWrap .title {
  padding-left: 30px;
}
h5 {
  font-size: 15px;
  background-color: #f5f5f5;
}
.conLeft,
.conRight {
  width: 38%;
  padding-left: 1%;
  .inputLable {
    margin-top: 30px;
  }
  .panelWrap .inputLable input {
    width: 60%;
  }
}

.markinfo {
  width: 57% !important;
  border-style: solid;
  border-width: 1px;
  border-color: var(--inputbc);
  border-radius: 3px;
  outline: none;
}

.conRight {
  padding-left: 30px;
  border-left: 1px solid #ccc;
  .titleTip {
    padding: 16px 0;
    border-bottom: 1px solid #ddd;
    font-size: 15px;
  }
  font-size: 13px;
  margin: 20px 30px;
  .inputLable {
    margin-top: 20px;
    .name {
      text-align: left !important;
    }
  }
}
.uploadDetails-title {
  margin: 15px 0 10px 0;
  display: inline-block;
}

.coordinateRead {
  width: 46% !important;
}

.downTem {
  cursor: pointer;
  padding: 5px 9px;
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
  border-radius: 3px;
  font-size: 12px;
  position: absolute;
  right: -144px;
  top: -8px;
}

.sanzhengImg {
  .uploadDetails-title {
    margin: 20px 0 10px 0;
  }
}
</style>
